    //
//  lookbookContentViewController.m
//  look.book
//
//  Created by Chih Yuan Liu on 3/18/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "lookbookContentViewController.h"
#import "FeedParser.h"
#import "LBImageGrabber.h"
#import "Reachability.h"
#import "CTPAlert.h"
#import "lookbookWebViewController.h"
#import "lookbookGalleryViewController.h"


@implementation lookbookContentViewController

@synthesize scrollview;
@synthesize firstview;
@synthesize refreshBtn;
@synthesize openGalleryBtn;

UIView * holderAll;
lookbookGalleryViewController * gvc;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

-(void)cleanContent{ 
	for(UIView * view in [scrollview subviews]){
		[view removeFromSuperview];
	}
}

-(void) layoutContent{
	UIView * view = nil;
	NSArray *subviews = [scrollview subviews];
	
	// reposition all image subviews in a horizontal serial fashion
	int i = 0;
    
	for (view in subviews)
	{
		if ([view isKindOfClass:[UIView class]] && view.tag > 0)
		{
            //UILabel* lbl = (UILabel*)[view viewWithTag:998];
            //NSLog(@"laying title:%d:%@ with tag:%d",i, lbl.text, view.tag);
			CGFloat curYLoc = 20;
			CGFloat curXLoc = (i * 1024) + 70;
			CGRect frame = view.frame;
			frame.origin = CGPointMake(curXLoc, curYLoc);
			view.frame = frame;
			view.tag = (i+1);
			i++;
		}
	}
	
	[scrollview setContentSize:CGSizeMake((i * 1024), 598)];
	CGPoint bottomOffset = CGPointMake(0,0);
	[scrollview setContentOffset: bottomOffset animated: YES];

}

-(void) addToThumb:(int)index holder:(UIView*)holder{
    [holderAll addSubview:holder ];
    //[gvc.scrollView addSubview:holder];
    //NSLog(@"gvc.scrollView count %d", [gvc.scrollView.subviews count]);
}

-(void) removeFromThumb:(int)index{
    [[holderAll.subviews objectAtIndex:49] removeFromSuperview];
}

-(void) loadContent:(NSArray*)updates{
	
	int count = [updates count];
	
	for (int i=0; i<count; i++) {
		LBFeedItem * item = [updates objectAtIndex:i];
		
		UIView *holder = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 870, 628)];
		holder.backgroundColor = [UIColor whiteColor];
		holder.tag = (i+1);
		
		UILabel * titleHolderLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 870, 56)];
		titleHolderLbl.backgroundColor = [UIColor blackColor];
		[holder addSubview:titleHolderLbl];
		
		UILabel * titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(16, 7, 840, 50)];
		titleLbl.backgroundColor = [UIColor blackColor];
		titleLbl.textColor = [UIColor whiteColor];
		titleLbl.font = [UIFont fontWithName:@"Helvetica" size:(36.0)];
        titleLbl.tag = 998;
        NSString * title = item.title;
        //NSLog(@"title: %@", title);
        title = [title stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
        //NSLog(@"title: %@", title);
		[titleLbl setText:title];
		[titleHolderLbl addSubview: titleLbl];
		
		UILabel * creatorLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 64, 154, 21)];
		[creatorLbl setText:[NSString stringWithFormat:@"BY: %@", item.dcCreator]];
		[holder addSubview:creatorLbl];
		
		UILabel * pubDateLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 99, 154, 21)];
		pubDateLbl.textColor = [UIColor darkGrayColor];
		pubDateLbl.font = [UIFont fontWithName:@"Helvetica" size:(12.0)];
		//NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
		//[dateFormat setDateFormat: @"MM dd, yyyy HH:mm:ss"]; // 2009-02-01 19:50:41 PST
		//NSDate * d = [[NSDate alloc] initWithString:item.pubDate];
		[pubDateLbl setText:item.pubDate];
		//[dateFormat release];
		//[d release];
		[holder addSubview:pubDateLbl];
		
		UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(252, 70, 540,540)];
		imageView.contentMode = UIViewContentModeTopLeft;
        imageView.tag = 999;
		[holder addSubview:imageView];
		
		[self addButtonsToView:holder];
		
		//[holder addSubview:button];
		
		UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(820,10,30,30)];
		[spinner startAnimating];
		[spinner setBackgroundColor:[UIColor blackColor]];
		[holder addSubview:spinner];
        
        
        //thumb
        int const imageheight = 140;
        int const imagewidth = 160;
        UIImageView *thumbImageView = [[UIImageView alloc] init];
        
        [thumbImageView addGestureRecognizer:
        [[[UITapGestureRecognizer alloc] initWithTarget:self
                                                  action:@selector(taponimage:)] autorelease]];
        
        UIView *thumbHolder = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 176, 250)];
        
        [thumbHolder setBackgroundColor:[UIColor whiteColor]];
        UIActivityIndicatorView *thumbSpinner = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(58,70,30,30)];
		[thumbSpinner startAnimating];
		[thumbSpinner setBackgroundColor:[UIColor whiteColor]];
		[thumbHolder addSubview:thumbSpinner];
       
        UILabel * thumbTitleLbl = [[UILabel alloc] initWithFrame:CGRectMake(9, 146, 160, 50)];
		thumbTitleLbl.backgroundColor = [UIColor whiteColor];
		thumbTitleLbl.textColor = [UIColor darkGrayColor];
		thumbTitleLbl.font = [UIFont fontWithName:@"Helvetica" size:(12.0)];
        title = title;
		[thumbTitleLbl setText:title];
        [thumbHolder addSubview:thumbTitleLbl];
        
        CGRect rect = CGRectMake(9,14,imagewidth, imageheight);//imageView.frame;
        rect.size.height = imageheight;
        thumbHolder.tag = (i+1);
        CGRect holderrect = thumbHolder.frame;
        holderrect.size.height = 200;
        thumbHolder.frame = holderrect;
        thumbImageView.frame = rect;
        thumbImageView.tag = 999;
        thumbImageView.userInteractionEnabled = YES;
        [thumbHolder addSubview:thumbImageView];
        [self addToThumb:i holder:thumbHolder];
		
		LBImageGrabber * grabber = [[LBImageGrabber alloc]initWithImageView: imageView indicator:spinner thumImage:thumbImageView thumbIndicator:thumbSpinner];
		[grabber grabImage: item.imageSrc];
		[grabbers addObject:grabber];
		[grabber release];
		
        //NSLog(@"adding title:%d:%@ with tag:%d",i, titleLbl.text, holder.tag);
		[scrollview insertSubview:holder atIndex:0];
        
        //remove "oldest" subview if excedes 50 subview
        //NSLog(@"subviews count:%d",[scrollview.subviews count]);
        if([scrollview.subviews count]>50){
            [[scrollview.subviews objectAtIndex:49] removeFromSuperview];
        }
        
		[holder release];
		[titleHolderLbl release];
		[titleLbl release];
        [thumbTitleLbl release];
		[pubDateLbl release];
		[creatorLbl release];
		[imageView release];
        [thumbImageView release];
		[spinner release];
        [thumbSpinner release];
		//[button release];
	}
	
	[self layoutContent];
}

-(void) addButtonsToView:(UIView*)holder{
	
	int offsetY = 135 ;
	
	UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[button setImage:[UIImage imageNamed:@"71-compass.png"] forState: UIControlStateNormal ];
	button.frame = CGRectMake(20.0, offsetY, 37.0, 37.0);
	[button addTarget:self action:@selector(openInSafari:)
	 forControlEvents:UIControlEventTouchUpInside];

	[holder addSubview:button];
	
	/*UIButton * button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[button1 setImage:[UIImage imageNamed:@"124-bullhorn.png"] forState: UIControlStateNormal ];
	button1.frame = CGRectMake(114.0, offsetY, 37.0, 37.0);
	[holder addSubview:button1];*/
	
	UIButton * button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[button2 setImage:[UIImage imageNamed:@"57-download.png"] forState: UIControlStateNormal ];
	button2.frame = CGRectMake(67.0, offsetY, 37.0, 37.0);
    [button2 addTarget:self action:@selector(saveToPhotos:)
	 forControlEvents:UIControlEventTouchUpInside];
	[holder addSubview:button2];
	
	/*UIButton * button3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[button3 setImage:[UIImage imageNamed:@"06-magnify.png"] forState: UIControlStateNormal ];
	button3.frame = CGRectMake(161.0, offsetY, 37.0, 37.0);
	[holder addSubview:button3];*/
	//button.tag = i;
}

-(void)openInSafari:(UIButton*)sender{
	int index = [model GetCount] -1 - sender.superview.tag;
	LBFeedItem * item = [model GetItemAtIndex:index];
	//NSLog(@"safari: %d",index);
	NSURL *url = [ [ NSURL alloc ] initWithString: item.link ];
    [[UIApplication sharedApplication] openURL:url];
    [url release];
}

-(void)saveToPhotos:(UIButton*)sender{
    UIImageView* imageView = (UIImageView*)[sender.superview viewWithTag:999];
    if(imageView){
        UIImage * image = imageView.image;
        if(image){
            UIImageWriteToSavedPhotosAlbum(image,nil,nil,nil);
            [[CTPAlert instance] alert:@"Saved..." withMessage:@"The look is saved to Photos Library!"];
        }
    }
}

lookbookWebViewController * webController;

-(void)moretouch:(UIButton*)sender{
	if(webController != nil)
		[webController release];
	LBFeedItem * item = [model GetItemAtIndex:sender.tag];
	webController = [[lookbookWebViewController alloc]initWithlink:item.link];
	webController.modalPresentationStyle = UIModalPresentationFormSheet;
	[self presentModalViewController:webController animated:YES];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return (interfaceOrientation ==
			UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

-(void)viewDidLoad{
    gvc = [[lookbookGalleryViewController alloc] initWithNibName:@"lookbookGalleryViewController" bundle:nil];
    holderAll = [[UIView alloc] init ];
	Reachability* internetReach;	
	internetReach = [[Reachability reachabilityForInternetConnection] retain];
	[internetReach startNotifier];
	NetworkStatus netStatus = [internetReach currentReachabilityStatus];
	if(netStatus == NotReachable){
		[[CTPAlert instance] alert:@"Ops..." withMessage:@"can not connect to lookboo.nu"];
	}else{
		grabbers = [[NSMutableArray alloc] init];
		model = [[LBFeedItemModel alloc] initWithDelegate:self];
		[firstview removeFromSuperview];
	}
	[internetReach release];
    //[[CTPAlert instance] alert:@"DEbug" withMessage:@"version 1.0.3"];

}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
	[grabbers release];
}

- (void)fetcherBegin:(LBFeedItemModel*)sender{
	refreshBtn.enabled = NO;
    openGalleryBtn.enabled = NO;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

- (void)fetcherEnd:(LBFeedItemModel*)sender{
	refreshBtn.enabled = YES;
    openGalleryBtn.enabled = NO;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

- (void)fetcherSucceeded:(LBFeedItemModel*)sender updates:(NSArray*) updates{
	//NSLog(@"updates count:%d", [updates count]);
	if([updates count] == 0){
		[[CTPAlert instance] alert:@"Nothing to update" withMessage:@"Patience is a virtue, Possess it if you can, Seldom found in woman, Never found in man"];
	}else{
		[self loadContent:updates];
	}
	
}
- (void)fetcherFailed:(LBFeedItemModel*)sender{}

-(IBAction)refresh:(id)sender{
	[model refresh];
}

-(IBAction)openGallery:(id)sender{
 
    gvc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    gvc.delegate = self;
    [self presentModalViewController:gvc animated:YES];
    if([holderAll.subviews count]>0){
        [gvc addToContent:holderAll];
        //NSLog(@"holderAll count:%d", [holderAll.subviews count]);
        [gvc relayoutContent];
    }
}

- (void)onThumbTouch:(lookbookGalleryViewController *)sender index:(int)index{
   
    CGPoint bottomOffset = CGPointMake(1024*index,0);
	[scrollview setContentOffset: bottomOffset animated: YES];
}

-(void)taponimage:(UITapGestureRecognizer*)sender {
    UIImageView * view = (UIImageView*)[(UITapGestureRecognizer*)sender view];
     
    int index = view.tag;
    NSLog(@"event sent index:%d", index);
    CGPoint bottomOffset = CGPointMake(1024*index,0);
	[scrollview setContentOffset: bottomOffset animated: YES];
    [gvc dismissModalViewControllerAnimated:TRUE];
}

@end
